package com.ctgu.demo.controller;

import com.ctgu.demo.utils.ApiResult;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/opsForZSet")
public class OpsForZSetController {

    private final RedisTemplate<String, Object> redisTemplate;

    public OpsForZSetController(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private static final String LEADERBOARD_KEY = "game:leaderboard";
    private static final String TASK_QUEUE_KEY = "task:queue";
    private static final String RECOMMENDATION_KEY = "recommendation:products";

    // http://localhost:8080/opsForZSet/leaderboard
    // 排行榜功能：维护一个排行榜，支持添加用户分数、查询前3名用户、查看某个用户的排名和分数。
    @GetMapping("leaderboard")
    public ApiResult leaderboard() {
        // 添加用户分数
        redisTemplate.opsForZSet().add(LEADERBOARD_KEY, "Alice", 300.0);
        redisTemplate.opsForZSet().add(LEADERBOARD_KEY, "Bob", 500.0);
        redisTemplate.opsForZSet().add(LEADERBOARD_KEY, "Charlie", 400.0);
        redisTemplate.opsForZSet().add(LEADERBOARD_KEY, "Alex", 200.0);
        redisTemplate.opsForZSet().add(LEADERBOARD_KEY, "Tom", 350.0);

        // 查询前 3 名用户
        Set<Object> topPlayers = redisTemplate.opsForZSet().range(LEADERBOARD_KEY, 0, 2);

        Map<String, Object> result = new HashMap<>();
        result.put("topPlayers", topPlayers);
        return ApiResult.success("前 3 名用户", result);
    }


    @PostConstruct
    public void initTasks() {
        long now = System.currentTimeMillis();
        redisTemplate.opsForZSet().add(TASK_QUEUE_KEY, "Task1", now + 5000);
        redisTemplate.opsForZSet().add(TASK_QUEUE_KEY, "Task2", now + 3000);
        redisTemplate.opsForZSet().add(TASK_QUEUE_KEY, "Task3", now + 7000);
    }

    // http://localhost:8080/opsForZSet/lazyQueue
    // 延迟队列：实现一个延迟队列，按任务的执行时间排序，优先执行分值最小的任务。
    @GetMapping("lazyQueue")
    public ApiResult lazyQueue() {
        long now = System.currentTimeMillis();

        // 查询当前可以执行的任务（分数 <= 当前时间）
        Set<Object> readyTasks = redisTemplate.opsForZSet().rangeByScore(TASK_QUEUE_KEY, 0, now);

        if (readyTasks != null && !readyTasks.isEmpty()) {
            for (Object task : readyTasks) {
                System.out.println("执行任务: " + task);
                // 在这里可以调用实际任务逻辑
            }
            // 删除已执行任务
            redisTemplate.opsForZSet().remove(TASK_QUEUE_KEY, readyTasks.toArray());
        }

        Map<String, Object> result = new HashMap<>();
        result.put("executedTasks", readyTasks);
        result.put("queueSize", redisTemplate.opsForZSet().zCard(TASK_QUEUE_KEY));
        return ApiResult.success("延迟队列任务消费", result);
    }

    // http://localhost:8080/opsForZSet/recommendation
    // 推荐系统：根据用户点击商品的次数，推荐分值最高的商品。
    @GetMapping("recommendation")
    public ApiResult recommendation() {
        // 添加商品点击次数
        redisTemplate.opsForZSet().add(RECOMMENDATION_KEY, "Product1", 5);
        redisTemplate.opsForZSet().add(RECOMMENDATION_KEY, "Product2", 8);
        redisTemplate.opsForZSet().add(RECOMMENDATION_KEY, "Product3", 3);

        // 增加商品点击次数
        redisTemplate.opsForZSet().incrementScore(RECOMMENDATION_KEY, "Product3", 4);

        // 获取推荐的前 2 件商品
        Set<Object> topProducts = redisTemplate.opsForZSet().reverseRange(RECOMMENDATION_KEY, 0, 1);

        Map<String, Object> result = new HashMap<>();
        result.put("topProducts", topProducts);
        return ApiResult.success("获取推荐的前 2 件商品",result);
    }
}
